package org.djw.basic.service.impl;

import org.djw.basic.constant.BaseConstants;
import org.djw.basic.exception.BusinessException;
import org.djw.basic.service.IVerifyCodeService;
import org.djw.basic.util.StrUtils;
import org.djw.user.domain.User;
import org.djw.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.security.Key;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class VerifyCodeServiceImpl implements IVerifyCodeService {
    @Autowired
    private IUserService userService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private JavaMailSender javaMailSender;

    @Override
    public void sendSmsCode(Map<String, String> params) {
        String phone = params.get("phone");
        String type = params.get("type");
        //空校验
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(type)){
            throw new BusinessException("手机号不能为空!!");
        }
        String businessKey = "";
        //根据type来判断是什么业务
        if ("register".equals(type)){
            //通过phone判断用户是否已经存在了
            User user = userService.loadByphone(phone);
            //如果存在,直接登录
            if (user != null){
                throw new BusinessException("用户已经存在,请重新输入");
            }
            businessKey = BaseConstants.BUSINESS_REGISTER_PREFIX + phone;
        }else if ("binder".equals(type)){
            businessKey = BaseConstants.BUSINESS_BINDER_PREFIX + phone;
        }//后续验证码登录等等功能可继续添加
        sendCode(businessKey);
    }

    /**
     * 发送验证码
     * @param businessKey
     */
    public void sendCode(String businessKey){
        String code = "";
        String key = businessKey;
        //获取之前的验证码
        Object codeValueTmp = redisTemplate.opsForValue().get(key);
        //如果codeValueTmp不为空,则证明还有验证码,3分钟过期时间未到
        if (codeValueTmp != null){
            //获取保存验证码时的时间
            Long oldTime = Long.valueOf(((String) codeValueTmp).split(":")[1]);
            //判断是否超过了一分钟
            if (System.currentTimeMillis() - oldTime <= 1*60*1000){
                //没有超过就是非法请求
                throw new BusinessException("小伙子,你还年轻,不要干这种事");
            }
            //超过一分钟,就使用旧的验证码
            code = ((String) codeValueTmp).split(":")[0];
            //否则就是新的请求,生成新的验证码,保存到redis并设置3分钟时间过期
        }else {
            //生成新的4位验证码
            code = StrUtils.getComplexRandomString(4);
        }
        //保存验证码
        //生成新的要保存到redis的value,code+:+当前系统时间
        String codeVal = code + ":" + System.currentTimeMillis();
        //保存到redis并设置有效期为3分钟
        redisTemplate.opsForValue().set(
                key,
                codeVal,
                3,
                TimeUnit.MINUTES
        );
        //调用SmsUtils发送短信
        //SmsUtils.sendSms(phone, "您的验证码是:"+code+",请在三分钟内使用,过期无效");
        System.out.println("您的验证码是:"+code+",请在三分钟内使用,过期无效");
    }








    @Override
    public void sendEmailCode(String email) {
        //判断邮箱是否为空
        if (email == null) {
            throw new BusinessException("邮箱不能为空");
        }
        //判断用户是否已经存在
        User user = userService.loadByemail(email);
        //如果user不为空,提示登录
        if (user != null) {
            throw new BusinessException("用户已经存在,请重新输入");
        }
        //准备验证码
        String code = "";
        String key = BaseConstants.BUSINESS_REGISTER_PREFIX + email;
        Object codeValueTmp = redisTemplate.opsForValue().get(key);
        //判断是否已经存在验证码,或者说超过三分钟
        if (codeValueTmp != null){
            Long oldTime = Long.valueOf(((String) codeValueTmp).split(":")[1]);
            //如果请求时间相差不到1分钟,则为恶意请求开骂
            if (System.currentTimeMillis() - oldTime <= 1*60*1000){
                throw new BusinessException("小伙子,不要瞎搞,不然你废了");
            }
            //获取已有的验证码
            code = ((String)codeValueTmp).split(":")[0];
            //如果已经超过三分钟(验证码已经失效或者第一次发送请求)
        }else {
            //调用StrUtils获取验证码
            code = StrUtils.getComplexRandomString(4);
        }
        //保存验证码到redis并设置有效时间为3分钟
        String codeVal = code + ":" + System.currentTimeMillis();
        redisTemplate.opsForValue().set(
                key,
                codeVal,
                3,
                TimeUnit.MINUTES);
        //发送邮件
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        //设置发送人
        simpleMailMessage.setFrom("362571828@qq.com");
        //邮件主题
        simpleMailMessage.setSubject("您的注册验证码为:");
        //邮件内容
        simpleMailMessage.setText("您的注册验证码为:"+code+"请在三分钟内使用,过期作废");
        //收件人
        simpleMailMessage.setTo(email);
        javaMailSender.send(simpleMailMessage);
    }
}
